package com.cbg.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Map;

/**
 * 标签数据源配置
 *
 * @author wangjuzheng
 * @date 2019-11-20
 **/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "labelEsSearchManageEntityManagerFactory", transactionManagerRef = "labelEsSearchManageTransactionManager"
        , basePackages = {"com.cbg.label.repository"})
public class LabelConfig {

    @Resource
    @Qualifier("labelDataSource")
    private DataSource dataSource;

    @Autowired
    private HibernateProperties hibernateProperties;

    @Autowired
    JpaProperties jpaProperties;

    @Bean(name = "labelEsSearchManageEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean labelEntityManagerFactory(EntityManagerFactoryBuilder builder) {

        Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
        LocalContainerEntityManagerFactoryBean em = builder.dataSource(dataSource)
                .properties(properties)
                .packages("com.cbg.label.entity")
                .persistenceUnit("masterPersistenceUnit")
                .build();
        return em;
    }

    @Bean(name = "labelEsSearchManageTransactionManager")
    PlatformTransactionManager labelTransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(labelEntityManagerFactory(builder).getObject());
    }
}